// 圣经问答游戏 - 主应用程序

class BibleQuizApp {
    constructor() {
        this.currentPage = 'welcomePage';
        this.audioEnabled = true;
        this.volume = 50;
        
        this.init();
    }

    // 初始化应用
    init() {
        // 等待DOM加载完成
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.setupApp());
        } else {
            this.setupApp();
        }
    }

    // 设置应用
    setupApp() {
        this.loadSettings();
        this.bindEvents();
        this.updateWelcomeStats();
        this.initializeAudio();
        
        console.log('圣经问答游戏初始化完成');
    }

    // 加载设置
    loadSettings() {
        const settings = gameStorage.getSettings();
        this.audioEnabled = settings.soundEnabled;
        this.volume = settings.volume;
        
        // 更新音频控制UI
        this.updateAudioControls();
        
        // 应用大字体设置
        if (settings.largeFont) {
            document.body.classList.add('large-font');
        }
    }

    // 绑定事件
    bindEvents() {
        // 难度选择按钮
        document.querySelectorAll('.difficulty-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const difficulty = e.currentTarget.dataset.level;
                this.startGame(difficulty);
            });
        });

        // 游戏控制按钮
        const nextBtn = document.getElementById('nextBtn');
        const quitBtn = document.getElementById('quitBtn');
        
        if (quitBtn) {
            quitBtn.addEventListener('click', () => quizGame.quitGame());
        }

        // 结果页面按钮
        const shareBtn = document.getElementById('shareBtn');
        const playAgainBtn = document.getElementById('playAgainBtn');
        const backToMenuBtn = document.getElementById('backToMenuBtn');
        
        if (shareBtn) {
            shareBtn.addEventListener('click', () => this.showShareModal());
        }
        
        if (playAgainBtn) {
            playAgainBtn.addEventListener('click', () => this.playAgain());
        }
        
        if (backToMenuBtn) {
            backToMenuBtn.addEventListener('click', () => this.backToMenu());
        }

        // 成就相关按钮
        const achievementsBtn = document.getElementById('achievementsBtn');
        const backFromAchievements = document.getElementById('backFromAchievements');
        
        if (achievementsBtn) {
            achievementsBtn.addEventListener('click', () => this.showAchievements());
        }
        
        if (backFromAchievements) {
            backFromAchievements.addEventListener('click', () => this.backToMenu());
        }

        // 音频控制
        const audioToggle = document.getElementById('audioToggle');
        const volumeSlider = document.getElementById('volumeSlider');
        
        if (audioToggle) {
            audioToggle.addEventListener('click', () => this.toggleAudio());
        }
        
        if (volumeSlider) {
            volumeSlider.addEventListener('input', (e) => this.setVolume(e.target.value));
        }

        // 键盘事件
        document.addEventListener('keydown', (e) => this.handleKeyPress(e));

        // 页面可见性变化（暂停/恢复游戏）
        document.addEventListener('visibilitychange', () => this.handleVisibilityChange());

        // 窗口大小变化
        window.addEventListener('resize', () => this.handleResize());
    }

    // 开始游戏
    startGame(difficulty) {
        quizGame.startGame(difficulty);
        this.switchToPage('gamePage');
        this.playClickSound();
    }

    // 显示分享弹窗
    showShareModal() {
        const gameStats = scoringSystem.getGameStats();
        shareSystem.showShareModal(gameStats);
    }

    // 再玩一次
    playAgain() {
        quizGame.restartGame();
        this.switchToPage('gamePage');
        this.playClickSound();
    }

    // 返回主菜单
    backToMenu() {
        this.switchToPage('welcomePage');
        this.updateWelcomeStats();
        this.playClickSound();
    }

    // 显示成就页面
    showAchievements() {
        quizGame.showAchievements();
        this.playClickSound();
    }

    // 切换页面
    switchToPage(pageId) {
        // 隐藏所有页面
        document.querySelectorAll('.page').forEach(page => {
            page.classList.remove('active');
        });
        
        // 显示目标页面
        const targetPage = document.getElementById(pageId);
        if (targetPage) {
            targetPage.classList.add('active');
            this.currentPage = pageId;
        }
    }

    // 更新欢迎页面统计
    updateWelcomeStats() {
        const stats = gameStorage.getUserStats();
        const totalQuestions = document.getElementById('totalQuestions');
        const totalBadges = document.getElementById('totalBadges');
        
        if (totalQuestions) totalQuestions.textContent = stats.totalQuestions;
        if (totalBadges) totalBadges.textContent = stats.totalBadges;
    }

    // 初始化音频
    initializeAudio() {
        // 设置音频系统
        if (window.mp3AudioSystem) {
            mp3AudioSystem.setVolume(this.volume / 100);
            mp3AudioSystem.setEnabled(this.audioEnabled);
            mp3AudioSystem.preloadSounds();
        }
    }

    // 更新音频控制UI
    updateAudioControls() {
        const audioToggle = document.getElementById('audioToggle');
        const volumeSlider = document.getElementById('volumeSlider');
        
        if (audioToggle) {
            audioToggle.textContent = this.audioEnabled ? '🔊' : '🔇';
            audioToggle.title = this.audioEnabled ? '关闭音效' : '开启音效';
        }
        
        if (volumeSlider) {
            volumeSlider.value = this.volume;
            volumeSlider.disabled = !this.audioEnabled;
        }
    }

    // 切换音频
    toggleAudio() {
        this.audioEnabled = !this.audioEnabled;
        this.saveAudioSettings();
        this.updateAudioControls();
        
        // 更新音频系统状态
        if (window.mp3AudioSystem) {
            mp3AudioSystem.setEnabled(this.audioEnabled);
        }
        
        if (this.audioEnabled) {
            this.playClickSound();
        }
    }

    // 设置音量
    setVolume(volume) {
        this.volume = parseInt(volume);
        this.saveAudioSettings();
        
        // 更新音频系统音量
        if (window.mp3AudioSystem) {
            mp3AudioSystem.setVolume(this.volume / 100);
        }
    }

    // 保存音频设置
    saveAudioSettings() {
        gameStorage.updateSettings({
            soundEnabled: this.audioEnabled,
            volume: this.volume
        });
    }

    // 播放点击音效
    playClickSound() {
        if (this.audioEnabled && window.mp3AudioSystem) {
            mp3AudioSystem.setVolume(this.volume / 100);
            mp3AudioSystem.setEnabled(this.audioEnabled);
            mp3AudioSystem.playSound('click');
        }
    }

    // 处理键盘按键
    handleKeyPress(e) {
        // ESC键返回主菜单
        if (e.key === 'Escape') {
            if (this.currentPage === 'gamePage') {
                quizGame.quitGame();
            } else if (this.currentPage !== 'welcomePage') {
                this.backToMenu();
            }
        }
        
        // 数字键选择答案（游戏中）
        if (this.currentPage === 'gamePage' && quizGame.gameActive) {
            const num = parseInt(e.key);
            if (num >= 1 && num <= 4) {
                const optionBtns = document.querySelectorAll('.option-btn');
                if (optionBtns[num - 1] && !optionBtns[num - 1].disabled) {
                    optionBtns[num - 1].click();
                }
            }
        }
        
        // 空格键继续下一题
        if (e.key === ' ' || e.key === 'Enter') {
            const nextBtn = document.getElementById('nextBtn');
            if (nextBtn && nextBtn.style.display !== 'none') {
                e.preventDefault();
                nextBtn.click();
            }
        }
    }

    // 处理页面可见性变化
    handleVisibilityChange() {
        if (document.hidden) {
            // 页面隐藏时暂停游戏
            if (quizGame && quizGame.gameActive) {
                quizGame.pauseGame();
            }
        } else {
            // 页面显示时恢复游戏
            if (quizGame && quizGame.gameActive) {
                quizGame.resumeGame();
            }
        }
    }

    // 处理窗口大小变化
    handleResize() {
        // 这里可以添加响应式调整逻辑
        // 比如重新计算布局、调整字体大小等
    }

    // 显示加载状态
    showLoading(message = '加载中...') {
        const loading = document.createElement('div');
        loading.id = 'loadingOverlay';
        loading.innerHTML = `
            <div class="loading-content">
                <div class="loading-spinner"></div>
                <div class="loading-text">${message}</div>
            </div>
        `;
        
        // 添加样式
        Object.assign(loading.style, {
            position: 'fixed',
            top: '0',
            left: '0',
            width: '100%',
            height: '100%',
            backgroundColor: 'rgba(0, 0, 0, 0.5)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            zIndex: '9999'
        });
        
        document.body.appendChild(loading);
    }

    // 隐藏加载状态
    hideLoading() {
        const loading = document.getElementById('loadingOverlay');
        if (loading) {
            loading.remove();
        }
    }

    // 显示错误消息
    showError(message, duration = 5000) {
        const error = document.createElement('div');
        error.className = 'error-message';
        error.textContent = message;
        
        Object.assign(error.style, {
            position: 'fixed',
            top: '20px',
            left: '50%',
            transform: 'translateX(-50%)',
            backgroundColor: '#e74c3c',
            color: 'white',
            padding: '12px 24px',
            borderRadius: '8px',
            fontSize: '16px',
            zIndex: '10000',
            opacity: '0',
            transition: 'opacity 0.3s ease'
        });
        
        document.body.appendChild(error);
        
        // 显示动画
        setTimeout(() => error.style.opacity = '1', 100);
        
        // 自动移除
        setTimeout(() => {
            error.style.opacity = '0';
            setTimeout(() => error.remove(), 300);
        }, duration);
    }

    // 显示成功消息
    showSuccess(message, duration = 3000) {
        const success = document.createElement('div');
        success.className = 'success-message';
        success.textContent = message;
        
        Object.assign(success.style, {
            position: 'fixed',
            top: '20px',
            left: '50%',
            transform: 'translateX(-50%)',
            backgroundColor: '#27ae60',
            color: 'white',
            padding: '12px 24px',
            borderRadius: '8px',
            fontSize: '16px',
            zIndex: '10000',
            opacity: '0',
            transition: 'opacity 0.3s ease'
        });
        
        document.body.appendChild(success);
        
        // 显示动画
        setTimeout(() => success.style.opacity = '1', 100);
        
        // 自动移除
        setTimeout(() => {
            success.style.opacity = '0';
            setTimeout(() => success.remove(), 300);
        }, duration);
    }

    // 获取应用状态
    getAppState() {
        return {
            currentPage: this.currentPage,
            audioEnabled: this.audioEnabled,
            volume: this.volume,
            gameState: quizGame ? quizGame.getGameState() : null,
            userStats: gameStorage.getUserStats()
        };
    }

    // 重置应用
    resetApp() {
        const confirmed = confirm('确定要重置所有数据吗？这将清除所有游戏记录和成就！');
        if (!confirmed) return;
        
        const success = gameStorage.resetAllData();
        if (success) {
            this.showSuccess('数据重置成功！');
            this.backToMenu();
            this.updateWelcomeStats();
        } else {
            this.showError('数据重置失败！');
        }
    }

    // 导出数据
    exportData() {
        try {
            const data = gameStorage.exportData();
            if (data) {
                const blob = new Blob([data], { type: 'application/json' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `bible-quiz-backup-${new Date().toISOString().split('T')[0]}.json`;
                a.click();
                URL.revokeObjectURL(url);
                this.showSuccess('数据导出成功！');
            }
        } catch (error) {
            console.error('导出数据失败:', error);
            this.showError('导出数据失败！');
        }
    }

    // 导入数据
    importData() {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = '.json';
        input.onchange = (e) => {
            const file = e.target.files[0];
            if (!file) return;
            
            const reader = new FileReader();
            reader.onload = (e) => {
                try {
                    const success = gameStorage.importData(e.target.result);
                    if (success) {
                        this.showSuccess('数据导入成功！');
                        this.updateWelcomeStats();
                    } else {
                        this.showError('数据导入失败！文件格式不正确。');
                    }
                } catch (error) {
                    console.error('导入数据失败:', error);
                    this.showError('导入数据失败！');
                }
            };
            reader.readAsText(file);
        };
        input.click();
    }

    // 检查更新
    checkForUpdates() {
        // 这里可以添加版本检查逻辑
        this.showSuccess('当前已是最新版本！');
    }

    // 显示帮助信息
    showHelp() {
        const helpContent = `
            <h3>游戏说明</h3>
            <ul>
                <li>选择难度等级开始游戏</li>
                <li>每题有四个选项，选择正确答案</li>
                <li>快速答题和连续答对可获得额外分数</li>
                <li>完成游戏可解锁成就徽章</li>
                <li>可以分享你的成绩到社交媒体</li>
            </ul>
            <h3>快捷键</h3>
            <ul>
                <li>数字键 1-4：选择答案</li>
                <li>空格键/回车键：下一题</li>
                <li>ESC键：退出游戏/返回主菜单</li>
            </ul>
        `;
        
        // 这里可以显示帮助弹窗
        alert(helpContent.replace(/<[^>]*>/g, ''));
    }
}

// 页面加载完成后初始化应用
window.addEventListener('load', () => {
    window.bibleQuizApp = new BibleQuizApp();
});

// 处理页面卸载
window.addEventListener('beforeunload', (e) => {
    if (quizGame && quizGame.gameActive) {
        e.preventDefault();
        e.returnValue = '游戏正在进行中，确定要离开吗？';
    }
});

// 处理错误
window.addEventListener('error', (e) => {
    console.error('应用错误:', e.error);
    if (window.bibleQuizApp) {
        bibleQuizApp.showError('应用出现错误，请刷新页面重试');
    }
});

// 处理未捕获的Promise错误
window.addEventListener('unhandledrejection', (e) => {
    console.error('未处理的Promise错误:', e.reason);
    if (window.bibleQuizApp) {
        bibleQuizApp.showError('网络或数据加载错误，请检查网络连接');
    }
});